package com.runfast.common.web.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.gxuc.runfast.bean.Cuser;
import com.runfast.common.Constants;
import com.runfast.common.utils.JsonUtils;
import com.runfast.common.utils.SessionContext;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.paotui.dao.model.RunfastCuser;
import com.runfast.paotui.dao.model.RunfastCuserExample;
import com.runfast.paotui.service.RunfastCuserService;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

public class JwtAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private RunfastCuserService cuserService;
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(TokenUtil.TOKEN);

        boolean flag = false;
        try {
            JWT decode = JWT.decode(token);
            Claim claim = decode.getClaim(TokenUtil.USER_ID);
            Integer userId = claim.asInt();
            flag = true;
        }catch (Exception e){

        }

        return flag||(!isLoginRequest(request, response) && isPermissive(mappedValue));
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JWTCreator.Builder builder = JWT.create();
        String accessToken = null;
        try {
            RandomStringGenerator generator = new RandomStringGenerator.Builder()
                    .withinRange('a', 'z').build();
            String randomLetters = generator.generate(9);

//            RunfastCuserExample runfastCuserExample = new RunfastCuserExample();
//            runfastCuserExample.createCriteria().andMobileEqualTo(token.getPrincipal().toString());
//            List<RunfastCuser> runfastCusers = cuserService.selectByExample(runfastCuserExample);
//            if(runfastCusers.isEmpty())throw new RuntimeException("用户不存在");

//            RunfastCuser runfastCuser = runfastCusers.get(0);


            Cuser cuser = (Cuser) RequestContextHolder.currentRequestAttributes().getAttribute(Constants.CURRENT_USER, RequestAttributes.SCOPE_SESSION);
            builder.withIssuer(TokenUtil.ISSUER).withClaim(TokenUtil.USER_ID, cuser.getId()).withClaim("r",randomLetters).withIssuedAt(new Date());
            accessToken = builder.sign(Algorithm.HMAC256(TokenUtil.SCRETE));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.getWriter().println(JsonUtils.getMapper().writeValueAsString(Result.ok("登录成功",accessToken)));
        return false;
    }
}
